using System.Collections;
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
public class Loading : MonoBehaviour
{
    public Scrollbar loadingScrollbar;   // 用于显示加载进度的Slider
    public Text loadingText;       // 显示加载进度的Text
    private bool isRequestCompleted = false;  // 模拟接口请求完成标志
    private List<string> prefabPaths;         // 存储资源路径


    void Start()
    {
        // 初始化 prefabPaths，指定Resources/PreLoad下所有预制件路径
        prefabPaths = new List<string>();
        LoadPrefabsInResources("PreLoadPrefabs");

        // 开始加载资源和模拟接口请求
        StartCoroutine(LoadAllPrefabs());
        // StartCoroutine(SimulateApiRequest());
        LoadJson();

        if (!PlayerPrefs.HasKey("ContainerStyle"))
        {
            PlayerPrefs.SetInt("ContainerStyle", 0);
            PlayerPrefs.Save();
            Data.StyleId = 0;
        }
    }

    // 加载 Resources/PreLoad 文件夹下的所有预制件
    private void LoadPrefabsInResources(string folderName)
    {
        // 使用 Resources.LoadAll 加载指定文件夹中的所有预制件
        Object[] prefabs = Resources.LoadAll(folderName, typeof(GameObject));

        foreach (Object prefab in prefabs)
        {
            // 将预制件的路径添加到 prefabPaths 列表中
            prefabPaths.Add($"{folderName}/{prefab.name}");
        }
    }

    // 模拟一个接口请求，等待请求返回才能结束 loading
    private IEnumerator SimulateApiRequest()
    {
        // 模拟等待接口请求完成
        yield return new WaitForSeconds(1f);  // 模拟3秒的请求时间
        isRequestCompleted = true;
    }

    private async void LoadJson()
    {
        // 异步加载资源
        JObject config = await Tools.LoadJsonAsync("Json/crazyFood");
        Data.gameConfig = config;
        Data.adsConfig = (JObject)config["ads_config"];
        Data.foodMenuCfg = (JArray)config["foodmenu_config"];
        Data.touxiangpeizhi = (JArray)config["character"];

        isRequestCompleted = true;
        //初始化Max
        AdsManager.Instance.InitializeAds();
        Debug.Log("游戏配置：" + JsonConvert.SerializeObject(config));
    }

    // 加载所有预制件
    private IEnumerator LoadAllPrefabs()
    {
        float totalPrefabs = prefabPaths.Count;
        float loadedPrefabs = 0f;

        foreach (string prefabPath in prefabPaths)
        {
            // 加载每个预制件
            ResourceRequest request = Resources.LoadAsync(prefabPath);
            while (!request.isDone)
            {
                // 更新进度条
                // loadingScrollbar.size = Mathf.Clamp01(request.progress);
                // loadingText.text = $"Loading... {Mathf.RoundToInt(request.progress * 100)}%";
                yield return null;
            }

            loadedPrefabs++;
            // 更新进度条
            loadingScrollbar.size = Mathf.Clamp01(loadedPrefabs / totalPrefabs);
            loadingText.text = $"LOADING {Mathf.RoundToInt(loadedPrefabs / totalPrefabs * 100)}%";
            Debug.Log("加载进度===>" + loadingText.text + loadingScrollbar.size.ToString());
            yield return null;
        }

        // 等待接口请求完成
        while (!isRequestCompleted)
        {
            yield return null;
        }

        // 隐藏loading页面
        HideLoadingScreen();
    }

    // 隐藏 loading 页面
    private async void HideLoadingScreen()
    {
        await FadeManager.Instance.FadeIn();
        gameObject.SetActive(false);
        GlobalEventManager.EmitEvent("EnterLobby");
        await FadeManager.Instance.FadeOut();
    }
}
